﻿namespace AntdUI_HamburgerMenuTabs.Common
{
    public class RandomCode
    {
        private const string charsUpper = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        private const string charsLower = "abcdefghijklmnopqrstuvwxyz";
        private const string charsNum = "0123456789";
        private const string charsSpecial = "!@#$%&";
        private readonly string chars = "";
        private readonly Random rnd = new();

        public RandomCode(bool UseUpper, bool UseLower, bool UseNum, bool UseSpecial)
        {
            if (UseUpper) chars += charsUpper;
            if (UseLower) chars += charsLower;
            if (UseNum) chars += charsNum;
            if (UseSpecial) chars += charsSpecial;
        }

        public int GetCharsLength()
        {
            return chars.Length;
        }

        public int GetMaxCount()
        {
            return (int)Math.Pow(chars.Length, chars.Length);
        }

        /// <summary>
        /// 获取唯一编码集合
        /// </summary>
        /// <param name="length">编码长度</param>
        /// <param name="cnt">编码个数</param>
        /// <param name="timesTotal">累计尝试次数</param>
        /// <param name="timesIgnore">累计忽略次数（取到了重复值）</param>
        /// <returns></returns>
        public HashSet<string> GetUniqueCodes(int length, int cnt, out int timesTotal, out int timesIgnore)
        {
            HashSet<string> res = [];
            timesTotal = 0;
            timesIgnore = 0;
            bool success;
            DateTime lastSuccessTime = DateTime.Now;
            while (res.Count < cnt)
            {
                string str = GenerateRandomString(length);
                timesTotal++;
                success = res.Add(str);
                if (success)
                {
                    lastSuccessTime = DateTime.Now;
                }
                else
                {
                    if ((DateTime.Now - lastSuccessTime).TotalSeconds > 30) break;
                    timesIgnore++;
                    continue;
                }
            }
            return res;
        }

        /// <summary>
        /// 获取编码集合
        /// </summary>
        /// <param name="length">编码长度</param>
        /// <param name="cnt">编码个数</param>
        /// <returns></returns>
        public List<string> GetCodes(int length, int cnt)
        {
            List<string> res = [];
            for (int i = 0; i < cnt; i++)
            {
                res.Add(GenerateRandomString(length));
            }
            return res;
        }

        /// <summary>
        /// 生成随机字符串
        /// </summary>
        /// <param name="length">编码长度</param>
        /// <returns></returns>
        public string GenerateRandomString(int length)
        {
            char[] buffer = new char[length];

            for (int i = 0; i < length; i++)
            {
                buffer[i] = chars[rnd.Next(chars.Length)];
            }
            return new string(buffer);
        }
    }
}